package cn.y.operation.framework.utils.dev;

import cn.y.operation.framework.constants.Constants;
import cn.y.operation.framework.enums.ResponseMsgEnum;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName: FileUtils
 * @author: 叶子豪
 * @create: 2020-09-16 16:11
 */
public class FileUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public static String saveIndexPic(MultipartFile picFile) throws IOException {
        String filename = picFile.getOriginalFilename();
        assert filename != null;
        return FileUtils.saveIndexPic(picFile, filename);
    }

    public static String saveIndexPic(MultipartFile picFile, String filename) throws IOException {
        String prefix = filename.substring(filename.lastIndexOf("."));
        filename = DateUtils.getDateToString(Constants.YYYYMMDDHHMMSS) + RandomStringUtils.random(2, true, true) + prefix;
        String filePath = Constants.FILE_PATH + DateUtils.getDateToString(Constants.YYYYMMDD);
        File file = new File(Constants.LOCALHOST_FILE_PATH + filePath, filename);///UpLoadFiles/20161117/2016111711070134.jpg
        if (!file.exists()) {
            if (!file.mkdirs()) {
                logger.error(ResponseMsgEnum.FILE_PATH_MKDIRS_ERR.getInfo());
                throw new IOException();
            }
        }
        picFile.transferTo(file);
        return filePath + "/" + filename;
    }

    public static boolean delFile(String filePath) throws IOException {
        File file = new File(Constants.LOCALHOST_FILE_PATH + filePath);
        return file.delete();
    }

    public static boolean delFile(File file) throws IOException {
        return file.delete();
    }

    //读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
